import { OpenAI } from "openai";
import { envConfig } from "../config/env-config.js";
import fs from "fs/promises";

interface TranslationOptions {
  source_lang: string;
  target_lang: string;
  terms?: { source: string; target: string }[];
  tm_list?: { source: string; target: string }[];
}

export class Translator {
  private client: OpenAI;
  private translationMemory: { source: string; target: string }[] = [];

  constructor() {
    if (!envConfig.DASHSCOPE_API_KEY) {
      throw new Error("DASHSCOPE_API_KEY is not configured in the environment.");
    }
    this.client = new OpenAI({
      apiKey: envConfig.DASHSCOPE_API_KEY,
      baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
    });
  }

  async loadTranslationMemory(filePath: string) {
    try {
      const fileContent = await fs.readFile(filePath, "utf-8");
      // Assuming the file contains a JSON array of objects with "source" and "target" keys
      // and that the content is already translated.
      const jsonData = JSON.parse(fileContent);
      if (Array.isArray(jsonData)) {
        this.translationMemory = jsonData.map((item: any) => ({
          source: item.source,
          target: item.target,
        }));
        console.log(`Translation memory loaded from ${filePath}`);
      }
    } catch (error: any) {
      if (error.code === 'ENOENT') {
        console.log(`Translation memory file not found at ${filePath}. Proceeding without it.`);
      } else {
        console.error("Failed to load or parse translation memory file:", error);
      }
      // Proceed without translation memory
    }
  }

  async translate(query: string, targetLang: "English" | "Chinese"): Promise<string> {
    const translation_options: TranslationOptions = {
      source_lang: "auto",
      target_lang: targetLang,
    };

    if (this.translationMemory.length > 0) {
      translation_options.tm_list = this.translationMemory;
    }

    try {
      const completion = await this.client.chat.completions.create({
        model: "qwen-mt-plus",
        messages: [{ role: "user", content: query }],
        // @ts-ignore - Pass translation_options directly as a top-level parameter
        translation_options: translation_options,
      });
      return completion.choices[0].message.content || query;
    } catch (error) {
      console.error("Error during translation:", error);
      return query; // Return original query on error
    }
  }
}
